package org.deltaset.samples.petclinic.user;

import javax.faces.component.UIViewRoot;
import javax.faces.context.FacesContext;
import javax.faces.event.PhaseEvent;
import javax.faces.event.PhaseId;
import javax.faces.event.PhaseListener;
import org.deltaset.faces.FacesUtils;

/**
 *
 * @author dmakariev
 */
public class PreferencesPhaseListener implements PhaseListener {

    @Override
    public void afterPhase(PhaseEvent event) {
        final UIViewRoot uIViewRoot = FacesContext.getCurrentInstance().getViewRoot();
        if (null == uIViewRoot) {
            return;
        }

        final PreferencesBean preferencesBean = FacesUtils.getManagedBean("preferencesBean", PreferencesBean.class);
        final String lang = FacesUtils.getParameter("lang");
        if (!"".equals(lang)) {
            preferencesBean.setCurrentLocaleLanguage(lang);
            preferencesBean.saveUserContext();
        }

        final String theme = FacesUtils.getParameter("theme");
        if (!"".equals(theme)) {
            preferencesBean.setThemeName(theme);
            preferencesBean.saveUserContext();
        }

        final String layout = FacesUtils.getParameter("layout");
        if (!"".equals(layout)) {
            preferencesBean.setLayoutName(layout);
            preferencesBean.saveUserContext();
        }

        final String showpager = FacesUtils.getParameter("showpager");
        if (!"".equals(showpager)) {
            preferencesBean.setShowPager(showpager);
            preferencesBean.saveUserContext();
        }

        final String fieldsetposition = FacesUtils.getParameter("fieldsetposition");
        if (!"".equals(fieldsetposition)) {
            preferencesBean.setFieldsetPosition(fieldsetposition);
            preferencesBean.saveUserContext();
        }
        //showpager, fieldsetposition
        uIViewRoot.setLocale(preferencesBean.getCurrentLocale());
    }

    @Override
    public void beforePhase(PhaseEvent event) {
        //do nothing
    }

    @Override
    public PhaseId getPhaseId() {
        return PhaseId.RESTORE_VIEW;
    }
}
